#!/bin/bash

if [ $# = 1 ]
then
    configScript=$1
else
    echo No configure script path passed in!!!
    exit
fi

if [ -f $configScript ]
then
    source $configScript
else
    echo Invalid configure script path!!!
    exit
fi

# Const
implScript=InitLinuxImpl.sh

if [ -f $implScript ]
then
    source $implScript
else
    echo No $implScript in current folder!!!
    exit
fi

############################
echo Now start EJ Deploy!
echo

### Deploy and Configure EJ ###
flag=$(GetConfigVar IsConfigureEJ $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Configure EJ

    ejGitPath=$(GetConfigVar LAMPGitEJ $OS $VER)
    AssertFunctionResult
    ejSrcDir=$(GetConfigVar LAMPGitDir $OS $VER)
    AssertFunctionResult
    ejDestDir=$(GetConfigVar LAMPDeployDir $OS $VER)
    AssertFunctionResult
    pkgDir=$(GetConfigVar FTPDownloadDir $OS $VER)
    AssertFunctionResult

    zipCmd=$(Get7zCmd)
    if [ $? != $SUCCESS ]
    then
        echo NO 7zip command!!!
        echo
        return
    fi

    # git clone
    if [ ! -d $ejSrcDir ]
    then
        mkdir -p $ejSrcDir
    fi
    cd $ejSrcDir
    git clone $ejGitPath
    cd $ejSrcDir/ej
    git submodule update --init --recursive

    # download pkg
    if [ -d $pkgDir ]
    then
        cd $pkgDir
        cmd=$(GetConfigVar FTPCmd $OS $VER)
        AssertFunctionResult
        user=$(GetConfigVar FTPLoginUser $OS $VER)
        AssertFunctionResult
        ip=$(GetConfigVar FTPIP $OS $VER)
        AssertFunctionResult
        FTPGet $cmd $user $ip $ftpPrePath/$ejshell
        FTPGet $cmd $user $ip $ftpPrePath/$extarrows
    else
        echo No FTP download dir: $pkgDir!!!
        exit -1
    fi

    # deploy
    pkgPath=${pkgDir}/$ejshell
    if [ -f $pkgPath ]
    then
        if [ ! -d $ejDestDir ]
        then
            mkdir -p $ejDestDir
        fi
        $zipCmd e $pkgPath -o$pkgDir
        if [ -f ${pkgPath%.7z} ]
        then
            tar xzvf ${pkgPath%.7z} -C $ejDestDir

            read -p "Make sure "'"python"'" command is usable and then continue ..." tmp
            $ejDestDir/Deploy.sh
        else
            echo ${pkgPath%.7z} NOT found!!!
        fi
    else
        echo No EJ shell package: $pkgPath!!!
    fi

    # LaTex
    echo Now need to install extarrows pkg for LaTex
    echo Uzip the package and copy to following path \(make sure daemon user could access it\):
    kpsepath tex | tr : '\n'
    echo May need run \"fmtutil-sys --all\" and \"texconfig rehash\" command
    read -p "..." tmp
fi
